package com.springboot.file.util.easyexcel.converter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.springboot.file.util.DateUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * LocalDateTime转换器
 */
@Slf4j
public class CustomLocalDateTimeConverter implements Converter<LocalDateTime> {

    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isEmpty(cellData)) {
            return null;
        }

        try {
            log.debug("日期时间转换 - 类型: {}, 值: {}", cellData.getType(), cellData.getData());

            if (CellDataTypeEnum.NUMBER.equals(cellData.getType())) {
                if (ObjectUtil.isEmpty(cellData.getNumberValue())) {
                    return null;
                }
                
                // Excel的日期起始点是1900-01-01，且有一个1900-02-29的bug需要处理
                // 如果大于60（1900-02-29）需要减1处理Excel的日期Bug
                double numericValue = cellData.getNumberValue().doubleValue();
                long wholeDays = (long) numericValue;
                
                // 处理Excel日期bug (1900-02-29不存在)
                if (wholeDays > 60) {
                    wholeDays -= 1;
                }
                
                // 转换天数部分为LocalDate
                LocalDate dateComponent = LocalDate.of(1900, 1, 1).plusDays(wholeDays - 1);
                
                // 处理时间部分 (小数部分表示一天的时间比例)
                double timeFraction = numericValue - Math.floor(numericValue);
                int totalSeconds = (int) Math.round(timeFraction * 24 * 60 * 60);
                int hours = totalSeconds / 3600;
                int minutes = (totalSeconds % 3600) / 60;
                int seconds = totalSeconds % 60;
                
                LocalTime timeComponent = LocalTime.of(hours, minutes, seconds);
                
                // 组合日期和时间
                return LocalDateTime.of(dateComponent, timeComponent);
            } else {
                if (cellData.getStringValue() == null || cellData.getStringValue().trim().isEmpty()) {
                    return null;
                }
                return DateUtil.convertObjToLdt(cellData.getStringValue());
            }
        } catch (Exception e) {
            log.error("日期时间转换失败 - 类型: {}, 值: {}, 错误: {}",
                    cellData.getType(), cellData.getData(), e.getMessage());
            return null;
        }
    }

    @Override
    public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (ObjectUtil.isEmpty(value)) {
            return new WriteCellData<>("");
        }
        return new WriteCellData<>(DateUtil.convertObjToString(value, DateUtil.DATE_FORMATTER_5));
    }
} 